package com.taoist_awei.blog.infrastructure.repository;

import com.taoist_awei.blog.core.ArticleEntity;
import com.taoist_awei.blog.core.ArticleRepository;
import com.taoist_awei.blog.core.ArticleStatus;
import com.taoist_awei.blog.core.ClassifyEntity;
import com.taoist_awei.blog.infrastructure.mapper.ArticleMapper;
import com.taoist_awei.blog.infrastructure.mapper.ClassifyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;

@Repository
public class MybatisArticleRepository implements ArticleRepository {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ClassifyMapper classifyMapper;

    @Override
    public Optional<List<ArticleEntity>> getArticleList(int page, int size, String status) {
        int begin = (page - 1) * size;
        return Optional.ofNullable(articleMapper.getArticleList(begin, size, status));
    }

    @Override
    public Optional<ArticleEntity> findArticleById(String id) {
        return Optional.ofNullable(articleMapper.findArticleById(id));
    }

    @Override
    public void saveArticle(ArticleEntity articleEntity) {
        if (articleMapper.findArticleById(articleEntity.getArticleId()) != null) {
            articleMapper.updateArticle(articleEntity);
        } else {
            articleMapper.insertArticle(articleEntity);
            ClassifyEntity entity = classifyMapper.findClassifyById(articleEntity.getClassifyId());
            classifyMapper.updateArticleNum(entity.getArticleNum() + 1);
        }
    }

    @Override
    public void deleteArticleById(String id) {
        articleMapper.deleteArticle(id);
    }

    @Override
    public void publish(String articleId) {
        articleMapper.status(ArticleStatus.PUBLISH, articleId);
    }

    @Override
    public void draft(String articleId) {
        articleMapper.status(ArticleStatus.DRAFT, articleId);
    }

    @Override
    public Optional<Integer> getSize() {
        return Optional.ofNullable(articleMapper.getSize());
    }
}
